import React, { Component } from 'react';
import { Dropdown, Modal, Menu, message, Empty, Checkbox } from 'antd';
import cass from 'classnames';
import lodash from 'lodash';
import FileList from '../../../components/FileList';
import RenameModal from '../../../components/UploadModal/RenameModal';
import PickerModal from '../../../components/UploadModal/PickerModal';
import s from './index.module.less';

import config from '../../../config';
import isSuccess from '../../../utils/error';
import taskServer from '../../../services/task';
import projectServer from '../../../services/project';

const confirm = Modal.confirm;
const { baseUrl } = config;
const { refleshFile, renameProjectFile, deleteProjectFile, saveFile: saveProjectFile, folderVisible, viewFile } = projectServer;
const { saveFile: saveTaskFile } = taskServer;

const emptyText = '';

function renderEmpty(description) {
    return <div className={s.empty}><Empty description={description} /></div>
}

export default class RenderMaterialItem extends Component {
    static defaultProps = {
        files: []
    }

    constructor(props) {
        super(props);
        this.state = {
            files: props.files
        };
    }

    componentWillReceiveProps(nextProps) {
        if (!lodash.isEqual(this.props.files, nextProps.files)) {
            this.setState({ files: nextProps.files })
        }
    }

    onHandleFolder = async (key, folder) => {
        if (key === '1') {
            const res = await folderVisible({
                folderid: folder.folderid,
                islawyervisible: folder.isclientfolder
            })
            // 成功更新数据
            if (isSuccess(res)) {
                message.success('设置成功！');
                this.refleshFile(() => {
                    const { refleshFolder } = this.props;
                    if (refleshFolder) refleshFolder() // 触发更新
                });
            }
        }
    }

    onCheckedChange = (e, vi, fi) => { // vi：文件序号  fi：文件夹序号
        // 先重置不同文件夹的值
        const files = this.state.files.map((f, fidx) => {
            const items = f.items.map((v, idx) => {
                if (fidx !== fi) {
                    return { ...v, checked: false }
                } else {
                    if (idx === vi) return { ...v, checked: e.target.checked }
                    else return v
                }
            });
            return { ...f, items };
        });
        this.setState({ files });
    }

    onCheckedAll = (e, fi) => {
        // 先重置不同文件夹的值
        const files = this.state.files.map((f, fidx) => {
            const items = f.items.map(v => {
                if (fidx !== fi) {
                    return { ...v, checked: false }
                } else {
                    return { ...v, checked: e.target.checked }
                }
            });
            return { ...f, items };
        });
        this.setState({ files });
    }


    // 不可改的函数名，父组件需要调用
    refleshFile = async (callback) => {
        const { detailData, stage, isShowInSlider, activeStageIndex } = this.props;
        const refleshData = await refleshFile({
            projectid: detailData.projectid,
            stageid: stage.stageid,
        })
        if (isSuccess(refleshData)) {
            // 如果是侧边栏显示的时候还要更新store里面对应的值，不然切换tap的时候会有问题
            const files = refleshData.data;
            if (isShowInSlider) {
                const newStage = { ...stage, files };
                const stages = detailData.stages.concat();
                stages[activeStageIndex] = newStage;
                const newDetailData = { ...detailData, stages };
                this.props.projectState.setStateValue('detailData', newDetailData);
            }
            this.setState({ files }, () => {
                callback && callback();
            });
        }
    }

    handleFile = (key, checkList) => {
        if (key === 'onRename') { // 重命名
            this.setState({ showRename: true, target: checkList[0] });
        } else if (key === 'onCopy') { // 复制文件
            this.setState({ pickerShow: true, target: checkList });
        } else {
            this[key](checkList);
        }
    }

    onRenameSure = async (newData, callback) => {
        const { detailData, stage } = this.props;
        const res = await renameProjectFile({
            projectid: detailData.projectid,
            stageid: stage.stageid,
            ...newData,
        })
        // 成功更新数据
        if (isSuccess(res)) {
            this.refleshFile(callback);
        }
    }

    onDownload = (files) => {
        // 由于使用a标签的默认download属性会有文件名无法自定义问题，要使用node+electron来下载
        const { ipcRenderer } = window.electron;
        const newFiles = files.map(f => ({ ...f, url: `${baseUrl}/file/${f.newfilename}` }));
        ipcRenderer.send('download', { files: newFiles });
    }

    onCopySure = async (v, callback) => {
        const { target } = this.state;
        let res;
        if (v.type === '1') {
            const files = target.map(t => ({
                folderid: v.folder.folderid, // 不知道有什么用的，但还是要传
                items: [{
                    folderid: v.folder.folderid, uploadfileid: t.uploadfileid,
                    filename: t.filename, sourcefilename: t.sourcefilename,
                    extension: t.extension,
                }]
            }));
            res = await saveProjectFile({
                projectid: v.project.recid,
                stageid: v.stage.stageid,
                files
            })
        } else if (v.type === '2') {
            const files = target.map(t => ({ filename: t.filename, sourcefilename: t.sourcefilename, uploadfileid: t.uploadfileid }));
            res = await saveTaskFile({
                taskid: v.task.recid,
                files
            })
        }

        // 成功更新数据
        if (isSuccess(res)) {
            message.success('转发文件成功');
            this.refleshFile(callback);
        }
    }

    onDelete = async (target) => {
        confirm({
            title: '确认删除已选的文件？',
            content: '',
            okText: "确定",
            cancelText: "取消",
            onOk: async () => {
                const { detailData, stage } = this.props;
                const queen = target.map(t => {
                    return deleteProjectFile({
                        projectid: detailData.projectid,
                        stageid: stage.stageid,
                        filerecid: t.fileid,
                    });
                });
                const allRes = await Promise.all(queen);
                console.log('--allResallResallResallRes--', allRes);

                // 成功更新数据
                this.refleshFile(() => {
                    message.success('删除成功！')
                });
            },
        });
    }

    onViewFile = async (file, icon) => {
        if (window.isOpenPreviewItem) {
            message.warn('正在打开文件，请稍后...');
            return;
        }
        if (!file.isviewed) {
            const res = await viewFile({ fileid: file.fileid });
            // 成功更新数据
            if (isSuccess(res)) {
                this.refleshFile();
            }
        }
        // 避免多次订阅，订阅打开应用的回调放在/src/pages/dashboard/index.js文件里面，添加isOpenPreviewItem标记正在打开
        window.isOpenPreviewItem = true;
        const { ipcRenderer } = window.electron;
        ipcRenderer.send("preview", { ...file, url: `${baseUrl}/file/${file.newfilename}` });
    }

    isLawyer = (stage) => { // 律师协作团队成员
        if (!stage) return false;
        const { islawyermember, islawyermanager, islawyerhost } = stage;
        return islawyermember || islawyermanager || islawyerhost;
    }

    // 未读在前面，已读在后面，并且按时间排序
    sortFiles = (files) => {
        if (files && files.length) {
            let newFiles = files;
            const hasRead = [];
            const unRead = [];
            files.forEach(f => {
                if (f.isviewed) hasRead.push(f);
                else unRead.push(f);
            });
            newFiles = [...unRead, ...hasRead];
            return newFiles;
        }
        return files;
    }

    render() {
        const { files, target, showRename, pickerShow } = this.state;
        const { create, col, needReflesh, detailData, stage, isShowInSlider } = this.props;
        if (!files || !files.length) return renderEmpty('暂无资料');
        const isLawyer = this.isLawyer(stage);
        const { islawyerhost, islawyermanager } = detailData;
        const isBoss = islawyerhost || islawyermanager;
        return (
            <div className={s.folder}>
                {
                    files.map((f, fi) => {
                        // 显示处理文件的按钮
                        const checkList = f.items.filter(v => v.checked);
                        const options = [
                            { key: 'onRename', name: '重命名', show: checkList.length === 1 && isLawyer },
                            { key: 'onDownload', name: '下载', show: checkList.length },
                            { key: 'onCopy', name: '转发', show: checkList.length },
                            { key: 'onDelete', name: '删除', show: checkList.length && isBoss },
                        ];
                        const btns = options.reduce((pre, v) => {
                            if (v.show) {
                                return pre.concat(
                                    <div
                                        onClick={() => this.handleFile(v.key, checkList)}
                                        key={v.key}
                                        className={cass(s.btn, { [s.btnBySide]: isShowInSlider })}
                                    >{v.name}</div>
                                )
                            }
                            else return pre;
                        }, []);

                        // 显示处理文件夹的按钮
                        let moreBtn = null;
                        if (f.isuserdefinefolder && isLawyer) {
                            const content = (
                                <Menu onClick={({ key }) => this.onHandleFolder(key, f, fi)}>
                                    <Menu.Item key={'1'}>设为委托人{f.isclientfolder ? '不可见' : '可见'}</Menu.Item>
                                </Menu>
                            );
                            moreBtn = (
                                <Dropdown overlay={content} trigger={['click']}>
                                    <span className={cass('mdi mdi-dots-horizontal', s.menu, 'mainColor')} />
                                </Dropdown>
                            )
                        };
                        const folderFiles = this.sortFiles(f.items || []);
                        const checkedAll = folderFiles.every(v => v.checked);
                        return (
                            <div className={cass(s.folderItem, { [s.folderItem2]: col === 2 })} key={f.folderid}>
                                <h3 className={cass(s.folderName, { [s.folderNameBySide]: isShowInSlider })}>
                                    <div className={s.folderTitle}>
                                        <Checkbox checked={checkedAll} onChange={e => this.onCheckedAll(e, fi)} />
                                        {f.isclientfolder ? <span className={cass('mdi mdi-account', s.client)} /> : null}
                                        {f.foldername || emptyText}
                                    </div>
                                    <div>{btns}</div>
                                    {moreBtn}
                                </h3>
                                <FileList
                                    col={col}
                                    isShowInSlider={isShowInSlider}
                                    files={folderFiles}
                                    mainKey={'fileid'}
                                    checkedKey={'checked'}
                                    onChange={(e, i) => this.onCheckedChange(e, i, fi)}
                                    onClick={this.onViewFile}
                                />
                            </div>
                        )
                    })
                }

                {create ? null : (
                    <RenameModal
                        data={target}
                        onChange={this.onRenameSure}
                        show={showRename}
                        onCancel={() => this.setState({ showRename: false })}
                    />
                )}

                {create ? null : (
                    <PickerModal
                        title="请选择目标文件夹/任务"
                        type={'1'}
                        needReflesh={needReflesh}
                        projectid={detailData.projectid}
                        projecttype={detailData.projecttype}
                        stageid={stage.stageid}
                        visible={pickerShow}
                        onOk={this.onCopySure}
                        onCancel={() => this.setState({ pickerShow: false })}
                    />
                )}
            </div>
        )
    }
}